<template>
  <div class="containner">
    <el-card class="box-card" style="width: 400px">
      <div slot="header" class="clearfix">
        <span>{{ admin.adminName }}</span>
      </div>
      <div>
        <!-- 头衔缩略图 -->
        <pan-thumb
          style="width: 100px; height: 100px; margin: 0px 0 0 100px"
          :image="admin.adminAvatar"
        />
        <!-- 文件上传按钮 -->
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="imagecropperShow = true"
          >更换头像
        </el-button>
        <!--
      v-show：是否显示上传组件
      :key：类似于id，如果一个页面多个图片上传控件，可以做区分
      :url：后台上传的url地址
      @close：关闭上传组件
      @crop-upload-success：上传成功后的回调 -->
        <!-- field的值要对应后端界面MultipartFile对应的名字 否则会上传失败 -->
        <image-cropper
          v-show="imagecropperShow"
          :width="300"
          :height="300"
          :key="imagecropperKey"
          :url="'/eduOss/fileOss'"
          field="file"
          @close="close"
          @crop-upload-success="cropSuccess"
        />
      </div>
      <div>
        生日：
        <el-tag>{{
          admin.adminBirth ? admin.adminBirth.split(" ")[0] : ""
        }}</el-tag>
      </div>
      <div>
        邮箱：
        <el-tag>{{ admin.adminEmail }}</el-tag>
      </div>
      <div>
        性别：
        <el-tag>{{ admin.adminSex == true ? "男" : "女" }}</el-tag>
      </div>
      <div
        style="display: flex; justify-content: space-around; margin-top: 10px"
      >
        <el-button type="primary" @click="showUpdateAdminInfo"
          >编辑信息</el-button
        >
        <el-button type="danger" @click="showUpdateAdminPwd"
          >修改密码</el-button
        >
      </div>
    </el-card>
    <el-dialog
      title="编辑信息"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <div>
        <table>
          <tr>
            <td>名称：</td>
            <td><el-input v-model="admin2.adminName"></el-input></td>
          </tr>
          <tr>
            <td>邮箱：</td>
            <td><el-input v-model="admin2.adminEmail"></el-input></td>
          </tr>
          <tr>
            <td>生日：</td>
            <td>
              <el-date-picker
                size="mini"
                v-model="admin2.adminBirth"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </td>
          </tr>
          <tr>
            <td>性别：</td>
            <td>
              <el-radio v-model="admin2.adminSex" :label="true">男</el-radio>
              <el-radio v-model="admin2.adminSex" :label="false">女</el-radio>
            </td>
          </tr>
        </table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateAdminInfo">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="更新密码" :visible.sync="PwdDialogVisible" width="30%">
      <div>
        <el-form
          :model="ruleForm"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="旧密码" prop="oldPss">
            <el-input
              type="password"
              v-model="ruleForm.oldPass"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="pass">
            <el-input
              type="password"
              v-model="ruleForm.pass"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input
              type="password"
              v-model="ruleForm.checkPass"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提交</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ImageCropper from "@/components/ImageCropper";
import PanThumb from "@/components/PanThumb";
import md5 from "md5-js";
import adminApi from "@/api/admin";
import cookie from "js-cookie";
export default {
  name: "adminInfo",
  components: {
    ImageCropper,
    PanThumb,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      PwdDialogVisible: false,
      ruleForm: {
        oldPass: "",
        pass: "",
        checkPass: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        oldPass: [{ validator: validatePass, trigger: "blur" }],
      },
      admin: {
        adminId: "",
        adminName: "",
        adminPwd: "",
        adminSex: "",
        adminBirth: "",
        adminAvatar: "",
        adminEmail: "",
        isDisabled: false,
        isDeleted: false,
      },
      admin2: {
        adminId: "",
        adminName: "",
        adminPwd: "",
        adminSex: "",
        adminBirth: "",
        adminAvatar: "",
        adminEmail: "",
        isDisabled: false,
        isDeleted: false,
      },

      //上传弹框组件是否显示
      imagecropperShow: false,
      imagecropperKey: 0, //上传组件key的值
    };
  },
  //设置监听事件
  // watch:{
  //   admin:{
  //     handler:function(){
  //       this.initAdminInfo()
  //     }
  //   }
  // },
  // mounted() {
  //   this.initAdminInfo();
  // },
  created() {
    this.initAdminInfo();
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.adminId = this.admin.adminId;
          this.ruleForm.oldPass = md5(this.ruleForm.oldPass);
          this.ruleForm.pass = md5(this.ruleForm.pass);
          this.ruleForm.checkPass = md5(this.ruleForm.pass);
          adminApi.toUpdateAdminPwd(this.ruleForm).then((response) => {
            cookie.set("token", "");
            this.$message({
              message: "修改密码成功",
              type: "success",
            });
            this.$router.replace({ path: "/" });
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //更新数据
    updateAdminInfo() {
      adminApi.toUpdateAdminInfo(this.admin2).then((response) => {
        if (response) {
          // console.log(response);
          this.dialogVisible = false;
          // this.initAdminInfo()
          const tokenStr = response.data.token;
          // tokenStr=Base64.decode(tokenStr)
          // console.log(tokenStr);
          cookie.set("token", tokenStr);
          this.$message({
            message: "更新成功",
            type: "success",
          });
          location.reload();
        }
      });
    },

    showUpdateAdminPwd() {
      this.PwdDialogVisible = true;
    },
    //显示对话框
    showUpdateAdminInfo() {
      this.dialogVisible = true;
      // this.admin2.adminSex = this.admin.adminSex
    },
    initAdminInfo() {
      adminApi.toGetAdminInfo().then((response) => {
        // console.log(response.data)
        this.admin = response.data.admin[0];
        this.admin2 = Object.assign({}, this.admin);
        // console.log(this.admin);
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch();
    },
    close() {
      //关闭上传弹框的方法
      this.imagecropperShow = false;
      this.imagecropperKey = this.imagecropperKey + 1;
    },
    cropSuccess(data) {
      // let adminData = new FormData();
      this.imagecropperShow = false;
      //上传之后接口返回图片地址 data.url等价于response.data.url 里面做了封装
      this.admin.adminAvatar = data.url;
      // 上传成功后，重新打开上传组件时初始化组件，否则显示上一次的上传结果
      this.imagecropperKey = this.imagecropperKey + 1;
      // this.admin.adminPwd = md5(this.admin.adminPwd)
      // console.log(this.admin.adminPwd)
      // adminData = Object.assign({}, this.admin);
      adminApi.toUpdateAdminInfo(this.admin).then((response) => {
        const tokenStr = response.data.token;
        cookie.set("token", tokenStr);
        this.$message({
          message: "头像更换成功",
          type: "success",
        });
        location.reload(); //手动f5刷新
      });
    },
  },
};
</script>
<style>
.containner {
  margin-left: 25%;
}
</style>
